package wang.aweb.childcar.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import wang.aweb.childcar.exception.CarException;
import wang.aweb.childcar.exception.CarExceptionEnum;
import wang.aweb.childcar.filter.UserFilter;
import wang.aweb.childcar.model.dao.OrderMapper;
import wang.aweb.childcar.model.pojo.Agent;
import wang.aweb.childcar.model.pojo.Device;
import wang.aweb.childcar.model.pojo.Member;
import wang.aweb.childcar.model.pojo.Order;
import wang.aweb.childcar.model.query.OrderParam;
import wang.aweb.childcar.model.vo.AgentVO;
import wang.aweb.childcar.model.vo.DeviceVO;
import wang.aweb.childcar.model.vo.OrderVO;
import wang.aweb.childcar.service.AgentService;
import wang.aweb.childcar.service.DeviceService;
import wang.aweb.childcar.service.MemberService;
import wang.aweb.childcar.service.OrderService;
import wang.aweb.childcar.tcpserver.ServerHandler;
import wang.aweb.childcar.util.MonthDataUtils;
import wang.aweb.childcar.util.SendMsgUtils;
import wang.aweb.childcar.util.StrUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AgentService agentService;
    @Override
    public Order findByOrderNo(String orderNo){
        Order order=orderMapper.selectByOrderNo(orderNo);
        return order;
    }
    @Override
    public void sendCmd(String orderNo, String cmd){
        Order currentOrder=this.findByOrderNo(orderNo);
        if(currentOrder.getStatus()==2){
            throw new CarException(CarExceptionEnum.ORDER_ALREADY_END);
        }
        Device currentDevice=deviceService.findById(currentOrder.getDeviceId());
        String channelId= ServerHandler.channelMap.get(currentDevice.getImei());
        String msg=SendMsgUtils.makeTcpMsg("12",currentDevice.getImei(),cmd);
        SendMsgUtils.sendToDevice(channelId,msg);
    }

    @Override
    public PageInfo getList(Integer page, Integer limit, OrderParam orderParam) {
        PageHelper.startPage(page,limit);
        List<Order> orderList=orderMapper.selectList(orderParam);
        List<OrderVO> orderVOList=orderListToOrderVOList(orderList);
        PageInfo orderPageInfo=new PageInfo<>(orderList);
        orderPageInfo.setList(orderVOList);
        return orderPageInfo;
    }



    private List<OrderVO> orderListToOrderVOList(List<Order> orderList){
        List<OrderVO> orderVOList=new ArrayList<>();
        for (int i = 0; i < orderList.size(); i++) {
            Order order =  orderList.get(i);
            orderVOList.add(orderToOrderVO(order));
        }
        return orderVOList;
    }
    @Override
    public Integer getOrderCount(){
        Map<String,Date> query=new HashMap<>();
        query.put("startTime",null);
        query.put("endTime",null);
        Integer count=orderMapper.getCount(query);
        return count;
    }
    @Override
    public Integer getAgentOrderCount(Integer agentId, Date starttime, Date endtime){
        Integer count=orderMapper.getAgentOrderCount(agentId,starttime,endtime);
        return count;
    }

    @Override
    public Order findNoDoneByMemberId(Integer id) {
        Order order=orderMapper.findNoDoneByMemberId(id);
        return order;
    }

    @Override
    public Integer getOrderMonthCount(){
        Map<String,Date> query=new HashMap<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        String date=sdf.format(new Date());
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            query.put("startTime", sdf1.parse(MonthDataUtils.getMonthBegin(date)));
            query.put("endTime",sdf1.parse(MonthDataUtils.getMonthEnd(date)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer count=orderMapper.getCount(query);
        return count;
    }
    @Override
    public Integer getOrderDayCount(){
        Map<String,Date> query=new HashMap<>();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        String date=sdf.format(new Date());
        query.put("startTime", MonthDataUtils.getDayStart(date));
        query.put("endTime",MonthDataUtils.getDayEnd(date));
        Integer count=orderMapper.getCount(query);
        return count;
    }
    private OrderVO orderToOrderVO(Order order){
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setPrice(order.getPrice()/100);
        DeviceVO device=deviceService.findVOById(order.getDeviceId());
        orderVO.setDeviceinfo(device);
        AgentVO agent=agentService.findVOById(order.getAgentId());
        orderVO.setAgentinfo(agent);
        orderVO.setCreate_time(order.getCreateTime());
        orderVO.setOrder_no(order.getOrderNo());
        orderVO.setStart_time(order.getStartTime());
        orderVO.setEnd_time(order.getEndTime());
        orderVO.setUserinfo(memberService.selectVOById(order.getMemberId()));
        return orderVO;
    }
    /**
     * 结束游玩
     * @param orderNo 订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doEnd(String orderNo){

            Member currentMember=memberService.selectById(UserFilter.memberThreadLocal.get().getId());
            Order currentOrder=this.findByOrderNo(orderNo);
            if(currentOrder.getStatus()==2){
                throw new CarException(CarExceptionEnum.ORDER_ALREADY_END);
            }
            Device currentDevice=deviceService.findById(currentOrder.getDeviceId());
            Agent currentAgent=agentService.getById(currentOrder.getAgentId());
            //发送消息

            String channelId= ServerHandler.channelMap.get(currentDevice.getImei());
            String msg=SendMsgUtils.makeTcpMsg("11",currentDevice.getImei(),"02");
            if(SendMsgUtils.sendToDevice(channelId,msg)==true){
                try{
                    String timestamp=String.valueOf(new Date().getTime());
                    Integer nowTime=Integer.valueOf(timestamp.substring(0,timestamp.length()-3));
                    String startTime=String.valueOf(currentOrder.getStartTime().getTime());
                    Integer startTimeI=Integer.valueOf(startTime.substring(0,startTime.length()-3));
                    //计算价格
                    Integer price=this.calPrice(currentDevice,nowTime-startTimeI);
                    //修改订单信息
                    currentOrder.setPrice(price);
                    currentOrder.setStatus(2);
                    currentOrder.setEndTime(new Date());
                    currentOrder.setTimelong((int)Math.ceil((float)nowTime-startTimeI)/60);
                    orderMapper.updateByPrimaryKeySelective(currentOrder);
                    //扣减余额并添加日志
                    memberService.consum(currentMember.getId(),price);
                    //分佣
                    //获取佣金额
                    Integer comrateMoney=(int)Math.floor((float)price*currentAgent.getComrate()/100);
                    //新增佣金并添加日志
                    agentService.updateMoneyById(orderNo,currentAgent.getId(),comrateMoney);
                    //设备修改状态
                    deviceService.updateStatus(currentDevice.getId(),1);
                }catch(Exception e){
                    throw new CarException(CarExceptionEnum.SYSTEM_ERROR);
                }
            }else{
                throw new CarException(CarExceptionEnum.DEVICE_NOT_ONLINE);
            }


    }
    private Integer calPrice(Device device,Integer seconds){
        return ((int)Math.ceil((double)seconds/60)*device.getMinprice());
    }
    /**
     * 开始游玩
     * @param imei 机器编号
     * @return 订单编号
     */
    @Override
    public String doStart(String imei){
        Order order=new Order();
        String ordersn= StrUtils.getOrderNo();
        Device currentDevice=deviceService.findByImei(imei);
        Member currentMember=memberService.selectById(UserFilter.memberThreadLocal.get().getId());
        if(currentMember.getMoney()<currentDevice.getMinprice()){
            throw new CarException(CarExceptionEnum.MONEY_NOT_ENOTH);
        }
        if(currentDevice.getStatus()!=1){
            throw new CarException(CarExceptionEnum.DEVICE_STATUS_ERROR);
        }
        //向机器发送信息
        String channelId= ServerHandler.channelMap.get(imei);
        String msg=SendMsgUtils.makeTcpMsg("11",imei,"01");
        if(SendMsgUtils.sendToDevice(channelId,msg)==true){
            //创建订单
            order.setOrderNo(ordersn);
            order.setMemberId(currentMember.getId());
            order.setDeviceId(currentDevice.getId());
            order.setAgentId(currentDevice.getAgentId());
            order.setPrice(0);
            order.setStatus(1);
            order.setStartTime(new Date());
            order.setEndTime(null);
            order.setCreateTime(new Date());
            String timeStamp=String.valueOf(new Date().getTime());
            order.setInputtime(timeStamp.substring(0,timeStamp.length()-3));
            orderMapper.insert(order);
            //修改机器状态
            deviceService.updateStatus(currentDevice.getId(),2);
            //修改用户agent
            memberService.updateAgentId(currentMember.getId(),currentDevice.getAgentId());
        }else{
            throw new CarException(CarExceptionEnum.IMEI_ERROR);
        }
        return ordersn;
    }
}
